<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">+新增</el-button>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="请输入">
        <el-input v-model="formInline.keyword" placeholder="请输入查询的姓名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="tableData" style="width: 100%" height="500px">
      <el-table-column
        v-for="item in tableLabel"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width ? item.width : 125"
      />
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="config.page"
      v-model:page-size="config.limit"
      :page-sizes="[10, 20, 30, 40]"
      layout="sizes, prev, pager, next"
      :total="config.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pager mt-4"
    />
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="30%"
  >
    <el-form :model="formUser" :inline="true" ref="userForm">
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="姓名"
            prop="name"
            :rules="[
              { required: true, message: '姓名是必填项', trigger: 'blur' },
              { min: 2, max: 5, message: '姓名长度在3到5', trigger: 'blur' },
            ]"
          >
            <el-input v-model.trim="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="年龄"
            prop="age"
            :rules="[
              { required: true, message: '年龄是必填项', trigger: 'blur' },
              { type: 'number', message: '年龄必须是数字', trigger: 'blur' },
            ]"
          >
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="性别"
            prop="sex"
            :rules="[
              { required: true, message: '性别是必选项', trigger: 'change' },
            ]"
          >
            <el-select v-model="formUser.sex" placeholder="请选择">
              <el-option label="女" value="0" />
              <el-option label="男" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="出生日期"
            prop="birth"
            :rules="[
              {
                type: 'date',
                required: true,
                message: '请选择日期',
                trigger: 'change',
              },
            ]"
          >
            <el-date-picker
              v-model="formUser.birth"
              type="date"
              label="出生日期"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item
            label="地址"
            prop="addr"
            :rules="[
              { required: true, message: '地址是必填项', trigger: 'blur' },
            ]"
          >
            <el-input v-model.trim="formUser.addr" placeholder="请输入地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <!-- <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          确认
        </el-button>
      </span>
    </template> -->
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  ref,
  reactive,
} from "vue";

export default defineComponent({
  setup() {
    const tableLabel = reactive([
      {
        prop: "name",
        label: "姓名",
      },
      {
        prop: "age",
        label: "年龄",
      },
      {
        prop: "sexLabel",
        label: "性别",
      },
      {
        prop: "birth",
        label: "出生日期",
        width: 200,
      },
      {
        prop: "addr",
        label: "地址",
        width: 320,
      },
    ]);
    const tableData = ref([]);
    const formInline = reactive({
      keyword: "",
    });
    const { proxy } = getCurrentInstance();
    const config = reactive({
      total: 0,
      limit: 10,
      page: 1,
    });
    const dialogFormVisible = ref(false);
    const formUser = reactive({
      name: "",
      age: "",
      sex: "",
      birth: "",
      addr: "",
    });
    const timeFormat = (time) => {
      var time = new Date(time);
      var year = time.getFullYear();
      var month = time.getMonth() + 1;
      var date = time.getDate();
      function add(m) {
        return m < 10 ? "0" + m : m;
      }
      return year + "-" + add(month) + "-" + add(date);
    };
    onMounted(() => {
      getUserDate(config);
    });
    const getUserDate = async (config) => {
      let resp = await proxy.$api.getUserDate(config);
      //console.log(resp);
      config.total = resp.count;
      tableData.value = resp.list.map((item) => {
        item.sexLabel = item.sex === 0 ? "女" : "男";
        return item;
      });
    };
    const handleCurrentChange = (page) => {
      //console.log(page);
      config.page = page;
      getUserDate(config);
    };
    const handleSizeChange = (pagesize) => {
      //console.log(page);
      config.limit = pagesize;
      getUserDate(config);
    };
    const handleSearch = () => {
      //console.log(page);
      config.name = formInline.keyword;
      getUserDate(config);
    };
    // const handleClose = (done) => {
    //   ElMessageBox.confirm("确定关闭吗？")
    //     .then(() => {
    //       proxy.$refs.userForm.resetFields();
    //       done();
    //     })
    //     .catch(() => {
    //       // catch error
    //     });
    // };
    const onSubmit = () => {
      proxy.$refs.userForm.validate(async (valid) => {
        if (valid) {
          if (action.value == "add") {
            //console.log(formUser);
            formUser.birth = timeFormat(formUser.birth);
            let resp = await proxy.$api.addUser(formUser);
            console.log(resp);
            if (resp) {
              dialogFormVisible.value = false;
              proxy.$refs.userForm.resetFields();
              getUserDate(config);
            }
          } else {
            //console.log(action.value);
            formUser.sex == "女" ? (formUser.sex = 0) : (formUser.sex = 1);
            let resp = await proxy.$api.editUser(formUser);
            console.log(resp);
            if (resp) {
              dialogFormVisible.value = false;
              proxy.$refs.userForm.resetFields();
              getUserDate(config);
            }
          }
        } else {
          ELMessage({
            showClose: true,
            message: "请输入正确内容",
            type: "error",
          });
        }
      });
    };
    const handleCancel = () => {
      dialogFormVisible.value = false;
      proxy.$refs.userForm.resetFields();
    };
    const action = ref("add");
    const handleAdd = () => {
      action.value = "add";
      dialogFormVisible.value = true;
    };
    const handleEdit = (row) => {
      action.value = "edit";
      //console.log(action.value);
      dialogFormVisible.value = true;
      row.sex == 0 ? (row.sex = "女") : (row.sex = "男");
      proxy.$nextTick(() => {
        Object.assign(formUser, row);
      });
      //Object.assign(formUser, row);
    };
    const handleDelete = (row) => {
      //console.log(row);
      ElMessageBox.confirm("确定删除吗？", "用户管理", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await proxy.$api.deleteUser({
            id: row.id,
          });
          ElMessage({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
          getUserDate(config);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消删除",
          });
        });
    };
    return {
      config,
      tableData,
      tableLabel,
      dialogFormVisible,
      action,
      formUser,
      formInline,
      handleCurrentChange,
      handleSizeChange,
      handleSearch,
      onSubmit,
      handleCancel,
      handleAdd,
      handleEdit,
      handleDelete,
    };
  },
});
</script>

<style lang="less" scoped>
.table {
  position: relative;
  height: 530px;
  .pager {
    position: absolute;
    left: 40%;
    bottom: -20px;
  }
}
.user-header {
  display: flex;
  justify-content: space-between;
}
</style>
